import "./index.less";
import { Form, Input, Toast } from "antd-mobile";
import { UserList } from "../user-list/index.jsx";
import {
  agreementList,
  idCardRegexp,
  phoneRegexp,
  userListData,
} from "@/contstants.js";
import { Agreement } from "@/components/agreement/index.jsx";
import { useEffect, useRef, useState } from "react";
import { SendCodeButton } from "./SendCodeButton.jsx";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useUserInfoStore } from "@/store/useUserStore.js";

export const ApplyBox = () => {
  const formRef = useRef(null);
  const [agree, setAgree] = useState(false);
  const [showSmsCode, setShowSmsCode] = useState(false);
  const [showUserInfo, setShowUserInfo] = useState(false);
  const [searchParams] = useSearchParams();
  const userInfoStore = useUserInfoStore();
  const navigate = useNavigate();

  const handleSendCode = () => {
    Toast.show("发送验证码");
  };

  const handleSubmitPhone = (values) => {
    userInfoStore.setData(values);
    Toast.show(`提交手机号 ${JSON.stringify(values)}`);
    setShowUserInfo(true);
  };

  const handleSubmitUserInfo = (values) => {
    userInfoStore.setData(values);
    Toast.show({
      content: `提交用户信息 ${JSON.stringify(values)}`,
      duration: 1000,
      afterClose: () => navigate("/insure", { replace: true }),
    });
  };

  const handleSubmit = (values) => {
    if (!agree) {
      Toast.show("请勾选同意协议");
      return;
    }
    if (showUserInfo) {
      handleSubmitUserInfo(values);
    } else {
      handleSubmitPhone(values);
    }
  };

  const handleFailed = ({ errorFields }) => {
    Toast.show(errorFields[0].errors[0]);
  };

  const validatePhone = (value) => {
    setShowSmsCode(phoneRegexp.test(value));
  };

  useEffect(() => {
    console.log(searchParams.get("link"));
  }, []);

  return (
    <div className={"apply-box"}>
      <div className={"inner"}>
        <div className={"title"}></div>
        <div className={"form"}>
          <Form
            layout="horizontal"
            onFinish={handleSubmit}
            onFinishFailed={handleFailed}
            ref={formRef}
            hasFeedback={false}
          >
            {!showUserInfo && (
              <>
                <Form.Item
                  label="手机号"
                  name={"phone"}
                  rules={[
                    { required: true },
                    { pattern: phoneRegexp, message: "手机号格式错误" },
                  ]}
                >
                  <Input
                    placeholder="您的信息将被严格保密"
                    maxLength={11}
                    onChange={validatePhone}
                  />
                </Form.Item>
                {showSmsCode && (
                  <Form.Item
                    label="验证码"
                    name={"code"}
                    extra={<SendCodeButton onSendCode={handleSendCode} />}
                    rules={[{ required: true }]}
                  >
                    <Input placeholder="请输入验证码" maxLength={6} />
                  </Form.Item>
                )}
              </>
            )}
            {showUserInfo && (
              <>
                <Form.Item
                  label="姓名"
                  name={"name"}
                  rules={[{ required: true }]}
                >
                  <Input placeholder="您的信息将被严格保密" />
                </Form.Item>
                <Form.Item
                  label="身份证"
                  name={"idCard"}
                  rules={[
                    { required: true },
                    { pattern: idCardRegexp, message: "身份证格式错误" },
                  ]}
                >
                  <Input placeholder="您的信息将被严格保密" maxLength={18} />
                </Form.Item>
              </>
            )}
          </Form>
          <div
            className={"submit-btn"}
            onClick={() => formRef.current.submit()}
          />
          <UserList data={userListData} />
          <Agreement
            data={agreementList}
            onChange={(value) => setAgree(value)}
          />
        </div>
      </div>
    </div>
  );
};
